
Eg.AnimationSheet = Eg.Class.extend({
  width: 8,
  height: 8,
  image: null,

  init: function (path, width, height) {
    this.width = width;
    this.height = height;

    this.image = new Eg.Image(path);
    this.image.load();
  }
});



Eg.Animation = Eg.Class.extend({
  sheet: null,
  timer: null,

  sequence: [],
  flip: { x: false, y: false },
  pivot: { x: 0, y: 0 },

  frame: 0,
  tile: 0,
  loopCount: 0,
  alpha: 1,
  angle: 0,


  init: function (sheet, frameTime, sequence, stop) {
    this.sheet = sheet;
    this.pivot = { x: sheet.width / 2, y: sheet.height / 2 };
    this.timer = new Eg.Timer();

    this.frameTime = frameTime;
    this.sequence = sequence;
    this.stop = !!stop;
    this.tile = this.sequence[0];
  },


  rewind: function () {
    this.timer.reset();
    this.loopCount = 0;
    this.tile = this.sequence[0];
    return this;
  },


  gotoFrame: function (f) {
    this.timer.set(this.frameTime * -f);
    this.update();
  },


  gotoRandomFrame: function () {
    this.gotoFrame(Math.floor(Math.random() * this.sequence.length))
  },


  update: function () {
    var frameTotal = Math.floor(this.timer.delta() / this.frameTime);
    this.loopCount = Math.floor(frameTotal / this.sequence.length);
    if (this.stop && this.loopCount > 0) {
      this.frame = this.sequence.length - 1;
    }
    else {
      this.frame = frameTotal % this.sequence.length;
    }
    this.tile = this.sequence[this.frame];
  },


  draw: function (targetX, targetY) {
    var bbsize = Math.max(this.sheet.width, this.sheet.height);

    // On screen?
    if (
		   targetX > Eg.sys.width || targetY > Eg.sys.height ||
		   targetX + bbsize < 0 || targetY + bbsize < 0
		) {
      return;
    }

    if (this.alpha != 1) {
      Eg.sys.context.globalAlpha = this.alpha;
    }

    if (this.angle == 0) {
      this.sheet.image.drawTile(
				targetX, targetY,
				this.tile, this.sheet.width, this.sheet.height,
				this.flip.x, this.flip.y
			);
    }
    else {
      Eg.sys.context.save();
      Eg.sys.context.translate(
				Eg.sys.getDrawPos(targetX + this.pivot.x),
				Eg.sys.getDrawPos(targetY + this.pivot.y)
			);
      Eg.sys.context.rotate(this.angle);
      this.sheet.image.drawTile(
				-this.pivot.x, -this.pivot.y,
				this.tile, this.sheet.width, this.sheet.height,
				this.flip.x, this.flip.y
			);
      Eg.sys.context.restore();
    }

    if (this.alpha != 1) {
      Eg.sys.context.globalAlpha = 1;
    }
  }
});